/*
 * @Author: Qimu
 * @Date: 2020-04-14 08:57:57
 * @LastEditors: Qimu
 * @LastEditTime: 2020-04-20 12:43:06
 * @Description: file content
 * @FilePath: \koa2_api\routes\api\news.js
 */
const router = require('koa-router')();
const query = require('../../module/utlis/query');
const tools = require('../../module/utlis/tools');
// const config = require('../../module/config/config');
const New = require('../../module/schama/new')// 引入schema user.js
const checkToken = require('../../module/middleware/token').admin()// 引入schema user.js

//后台前端接口
router
  /* @route POST api/news    
  *  @desc:文章信息接口地址
  */
  .post('/new', checkToken, async (ctx) => {
    ctx.status = 200;
    let data = {
      title: ctx.request.body.title,
      content: ctx.request.body.content,
    }
    let saveResult = await query.save(New, data)//保存新闻数据
    console.log(saveResult);
    ctx.body = {
      'code': 1,
      'data': data,
      'message': 'data数据保存成功'
    }
  })

  //前台前端接口
  /* @route POST api/news    
    *  @desc:文章信息接口地址
    */
  .get('/list', checkToken, async (ctx) => {
    ctx.status = 200;
    let pageNum = 1;//第1条开始
    let pageSize = 2;//每页2条
    let count = await query.count(New); //列表总条数
    console.log(' $count', count);
    New.find({})
      .skip((pageNum - 1) * pageSize)
      .limit(pageSize)
      .sort({ '_id': 1 })
      .exec((err, doc) => {
        console.log(doc);
        // try {
        //   if (!err && doc) {
        //     return res.json({ code: 0, totalCount: count, msg: '列表获取成功', data: doc })
        //   }
        //   res.json({ code: 1, msg: '后端出错' })
        // } catch (e) {
        //   res.json({ code: 1, msg: '后端出错' })
        // }
      })
    // let limitResult = await query.find(New, {});//查询新闻数据
    // console.log(limitResult.limit(number));
    // let limitResult1 = await New.find({}, (err, res) => {
    //   err ? console.log(err) : console.log(res)
    // }).skip(number).limit(3)
    // console.log(limitResult1);

    // ctx.body = {
    //   'code': 1,
    //   'data': limitResult1,
    //   'message': `查询${number}数据`
    // }
  })

module.exports = router;